package com.copy;

import java.util.HashMap;
import java.util.Map;

public class CopyRandomPointer2 {

    public Node copyRandomList(Node head) {
        if(head == null) return head;

        copyNext1(head);
        copyRandom1(head);
        return split1(head);
    }

    private Node split1(Node head) {
        if(head == null) return head;
//        Node newHead = head.next;
//
//        while (head != null){
//            Node temp = head.next;
//            head.next = temp.next;
//
//            head = head.next;
//            if(head != null){
//                temp.next = head.next;
//            }
//        }
//        return newHead;

        Node newHead = head.next;

        while (head != null){
            Node temp = head.next; // temp -> 1'
            head.next = temp.next; // 1 -> 2

            head = head.next;
            if(head != null){
                temp.next = head.next; // 1' -> 2'
            }
        }
        return newHead;
    }

    private void copyRandom1(Node head) {
        while (head != null){
            Node random = head.random;
            if(random != null){
                head.next.random = random.next;
            }
            head = head.next.next;
        }
    }

    private void copyNext1(Node head) {
        while (head != null){
            Node copyNode = new Node(head.val);
            copyNode.next = head.next;
            head.next = copyNode;
            head = copyNode.next;
        }
    }

    private Node split(Node head) {
        Node newHead = head.next;

        while (head != null){
            Node temp = head.next; // 1'
            head.next = temp.next; // 1 -> 2

            head = head.next;
            if(head != null)
                temp.next = head.next; // 1' -> 2'
        }
        return newHead;
    }

    private void copyRandom(Node head) {
        while (head != null){
            Node random = head.random;
            if (random != null)
                head.next.random = random.next;

            head = head.next.next;
        }
    }

    private void copyNext(Node head) {

        while (head != null){
            Node copy = new Node(head.val);// 1'
            copy.next = head.next;// 1' -> 2
            head.next = copy; // 1 -> 1'

            head = copy.next;
        }
    }
}
